var CommentBox=React.createClass({
	getInitialState:function(){
		return {data:[]};
	},
	loadFromServer:function(){
		$.ajax({
			url:this.props.url,
			dataType:"json",
			success:function(data){
				this.setState({data:data});
			}.bind(this),
			error:function(xhr, status, err){
				console.log(this.props.url, status, err.toString());
			}.bind(this)
		});
	},
	handleCommentSubmit: function(comment) {
	    // TODO: 回掉函数
		console.log(comment);
	  },
	componentDidMount:function(){
		this.loadFromServer();
		setInterval(this.loadFromServer,this.props.pollInterval);
	},
	render:function(){
		return (
			<div className="commentBox">
				<h1>Comments</h1>
				<CommentList data={this.state.data} />
				<CommentForm onCommentSubmit={this.handleCommentSubmit}/>
			</div>
			);
	}
}); 

var CommentList=React.createClass({
	render:function(){
		var commentNodes="";
		if(this.props.data){
			commentNodes=this.props.data.map(function(comment){
				return (
						<Comment author={comment.anthor} key={comment.id}>
							{comment.text}
						</Comment>
				);
			});
		}
		/*this.props.data.map(function(comment){
			return (
					<Comment author={comment.anthor} key={comment.id}>
						{comment.text}
					</Comment>
			);
		});*/
		return (
			<div className="commentList">
				{commentNodes}
			</div>
		);
	}
});
var CommentForm=React.createClass({
	handleSubmit:function(e){
		e.preventDefault();
		var author=this.refs.author.value.trim();
		var text=this.refs.text.value.trim();
		if(author && text){
			this.props.onCommentSubmit({author: author, text: text});
			this.refs.author.value='';
			this.refs.text.value='';
		}

		
	},
	render:function(){
		return (
				<form className="commentForm" onSubmit={this.handleSubmit}>
					<input type="text" placeholder="Your name" ref="author"/>
					<input type="text" placeholder="Say something..." ref="text"/>
					<input type="submit" value="Post" />
		      </form>
		
		);
	}
});
var Comment=React.createClass({
	rawMarkup: function() {
	    var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
	    return { __html: rawMarkup };
	  },
	render:function(){
		return (
			<div>
				<h2>{this.props.author}</h2>
				 <span dangerouslySetInnerHTML={this.rawMarkup()} />
				
			</div>	
		);
	}
});
ReactDOM.render(<CommentBox url="js/data.json" pollInterval="2000"/> ,document.getElementById("content"));